package cz.uvn.orthopedy.server.jdo;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import cz.uvn.orthopedy.client.entity.Doctor;

public final class DoctorJdo {
	
	private DoctorJdo() {
	}

	public static void editDoctor(Doctor doctor) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Doctor.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			query.setUnique(true);
			Doctor result = (Doctor) query.execute(doctor.getId());
			if (result != null) {
				result.setName(doctor.getName());
				result.setSurname(doctor.getSurname());
				result.setTitle(doctor.getTitle());
				result.setAdmin(doctor.isAdmin());
			}
		} finally {
			pm.close();
		}
	}

	public static void createDoctor(Doctor doctor) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			pm.makePersistent(doctor);
		} finally {
			pm.close();
		}
	}
	
	public static void deleteDoctor(Doctor doctor) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Doctor.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			@SuppressWarnings("unchecked")
			List<Doctor> result = (List<Doctor>) query.execute(doctor.getId());
			assert result.size() == 1;
			pm.deletePersistent(result.get(0));
		} finally {
			pm.close();
		}
	}

	public static Doctor[] getDoctors() {
		Doctor[] doctors = null;
		PersistenceManager pm = PMF.get().getPersistenceManager();
		pm.setDetachAllOnCommit(true);
		try {
			Query q = pm.newQuery(Doctor.class);
			q.setOrdering("surname");
			@SuppressWarnings("unchecked")
			List<Doctor> result = (List<Doctor>) q.execute();
			doctors = new Doctor[result.size()];
			for (int i = 0; i < result.size(); i++) {
				Doctor doc = result.get(i);
				doctors[i] = new Doctor(doc.getId(), doc.getName(), doc.getSurname(), doc.getTitle(), doc.isAdmin());
			}
		} finally {
			pm.close();
		}
		return doctors;
	}

	public static Doctor getDoctor(Long id) {
		PersistenceManager pm = PMF.get().getPersistenceManager();
		try {
			Query query = pm.newQuery(Doctor.class);
			query.setFilter("id == idParam");
			query.declareParameters("Long idParam");
			query.setUnique(true);
			return (Doctor) query.execute(id);
		} finally {
			pm.close();
		}
	}

}
